package com.leyou.cart.interceptors;

import com.leyou.cart.config.JwtProperties;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class UserInfoInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties props;


    private static ThreadLocal<UserInfo> tl = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1，请求中获取cookie
        //2,从cookie中获取token
        try {
            String token = CookieUtils.getCookieValue(request, props.getUser().getCookieName());

            //3，从token中获取用户的信息
            Payload<UserInfo> infoFromToken = JwtUtils.getInfoFromToken(token, props.getPublicKey(), UserInfo.class);

            //把获取到的用户的信息存入threadLocal
            tl.set(infoFromToken.getInfo());

            log.info("请求进来后，成功获取到用户的信息");
            return true;//拦截器放行
        } catch (Exception e) {
            log.error("请求进来后，获取用户信息失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//返回状态码401，表示未授权不能操作
            return false; //请求拦截
        }

    }

    //获取userInfo
    public UserInfo getUserInfo() {
        return tl.get();//从threadLocal中获取
    }


    //业务完成时，作为拦截器中最后执行的方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        tl.remove();//在线程离去时，把其存储的数据销毁
    }
}
